# -*- coding: utf-8 -*-

from .items import NovelItem
from .model import get_session, Novel


# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


class NovelPipeline(object):
    def process_item(self, item, spider):
        session = get_session()
        if isinstance(item, NovelItem):

            """
            1.  如果小说不存在, 则创建小说; 如果已经存在, 则更新数据
            """
            novel_model = session.query(Novel).filter(
                Novel.website_url == item["website_url"],
                Novel.novel_author == item["novel_author"],
                Novel.novel_name == item["novel_name"],
                Novel.novel_url == item["novel_url"],
            ).one_or_none()

            if not novel_model:
                novel_model = Novel()
                novel_model.website_url = item["website_url"]
                novel_model.novel_url = item["novel_url"]
                novel_model.novel_name = item["novel_name"]
                novel_model.novel_cover_url = item["novel_cover_url"]
                novel_model.novel_desc = item["novel_desc"]
                novel_model.novel_author = item["novel_author"]
                novel_model.novel_lasted_chapter_name = item["novel_lasted_chapter_name"]
                novel_model.novel_lasted_chapter_url = item["novel_lasted_chapter_url"]
                novel_model.novel_lasted_update = item["novel_lasted_update"]
                session.add(novel_model)
                session.commit()
        return item
